package main

import (
	"flag"
	"fmt"
	"log"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/tealeg/xlsx"
)

var modbusCfg = struct {
	URL     string
	Name    string
	SlaveId int
}{
	URL:  "192.168.1.37:502",
	Name: "zjzm_rhb",
}

var router *gin.Engine

// var logFile *os.File

func main() {
	// 获取运行时传参
	var name string
	var url string
	var port string
	var slaveId int

	flag.StringVar(&name, "name", "zjzm_rhb", "a name to parse")
	flag.StringVar(&url, "url", "192.168.1.37:502", "url of station")
	flag.StringVar(&port, "port", "8080", "port")
	flag.IntVar(&slaveId, "slaveId", 1, "slaveId")

	flag.Parse()
	fmt.Println("name: ", name)
	fmt.Println("url: ", url)
	modbusCfg.Name = name
	modbusCfg.URL = url
	modbusCfg.SlaveId = slaveId
	// initLog()
	// defer logFile.Close()

	parseExcel()
	initDB()

	router = gin.Default()
	// router.Use(gin.LoggerWithWriter(logFile))
	// router.Use(gin.RecoveryWithWriter(logFile))
	// router.Use(ErrorLoggingMiddleware())

	initHttpRoutes()
	initWs()
	go initModbus()

	// 启动 Gin 服务器
	err := router.Run(":" + port)
	if err != nil {
		log.Fatal("Server startup error:", err)
	}
}

// func initLog() {
// 	logFile, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
// 	if err != nil {
// 		log.Fatal(err)
// 	}

// 	// 设置日志输出到文件
// 	log.SetOutput(logFile)

// 	// 设置日志前缀和标志，这里的标志包括日志时间、日期和源文件信息
// 	log.SetPrefix("LOG: ")
// 	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)

// 	// 记录日志
// 	// log.Println("This is a test log entry")
// }

// func ErrorLoggingMiddleware() gin.HandlerFunc {
// 	return func(c *gin.Context) {
// 		c.Next() // 处理请求

// 		// 检查是否有错误
// 		if len(c.Errors) > 0 {
// 			for _, e := range c.Errors {
// 				// 将错误记录到日志
// 				log.Printf("ERROR: %s\n", e.Error())
// 			}
// 		}
// 	}
// }

/* 解析点表excel */
func parseExcel() {
	file, err := xlsx.OpenFile("files/" + modbusCfg.Name + ".xlsx")
	if err != nil {
		log.Fatal(err)
	}
	for _, sheet := range file.Sheets {
		typeCol := 1
		remarkCol := 2
		nameCol := 3
		belongCol := 4
		errorCodeColNum := 7

		for i, row := range sheet.Rows {
			if i < 1 {
				continue
			}
			if (len(row.Cells) > typeCol && row.Cells[typeCol].String() != "") &&
				(len(row.Cells) > nameCol && row.Cells[nameCol].String() != "") {
				name := row.Cells[nameCol].String()
				nameSplit := strings.Split(name, "_")
				hold, _ := strconv.Atoi(nameSplit[0])
				hold = hold%40000 - 1
				ptType := row.Cells[typeCol].String()
				boolIndex := -1
				if ptType == "BOOL" {
					indexInt, _ := strconv.Atoi(nameSplit[1])
					boolIndex = indexInt
				}
				ErrorCode := func() string {
					if errorCodeColNum < len(row.Cells) && row.Cells[errorCodeColNum] != nil {
						return row.Cells[errorCodeColNum].String()
					}
					return ""
				}()
				singlePt := PtStruct{
					Name:      row.Cells[nameCol].String(),
					Type:      row.Cells[typeCol].String(),
					Belong:    row.Cells[belongCol].String(),
					Remark:    row.Cells[remarkCol].String(),
					ErrorCode: ErrorCode,
					Value:     0,
					Hold:      hold,
					BoolIndex: boolIndex,
				}
				ptArray = append(ptArray, singlePt)
			}
		}

		// fmt.Println(ptArray)
	}
}
